import { login, logout, getUserInfo } from "@/api/user";
import { getMassage, getAuditMassage } from "@/api/massage";
import { getDict } from "@/api/dict";
import {
  getToken,
  setToken,
  removeToken,
  getOssUrl,
  setOssUrl,
  removeOssUrl,
  getId,
  setId,
  removeId,
  getWorkerId,
  setWorkerId,
  removeWorkerId
} from "@/utils/auth";
import router, { resetRouter } from "@/router";

const state = {
  token: getToken(),
  name: "",
  userName: "",
  avatar: "",
  roles: [],
  id: "",
  type: "",
  ossUrl: "",
  info: {},
  msgCount: 0,
  timer: null,
  auditCount: {
    firstAudit: 0,
    fzBrandCount: 0,
    fzMaterialsCount: 0,
    fzMerchantCount: 0,
    fzServiceCount: 0,
    fzServiceMerchantCount: 0,
    registerCount: 0,
    secondAudit: 0,
    serviceFirstAudit: 0,
    serviceSecondAudit: 0,
    zzBrandCount: 0,
    zzMaterialsCount: 0,
    zzMerchantCount: 0,
    zzServiceCount: 0,
    zzServiceMerchantCount: 0
  },
  auditTimer: null
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_USERNAME: (state, userName) => {
    state.userName = userName;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_ID: (state, id) => {
    state.id = id;
  },
  SET_TYPE: (state, type) => {
    state.type = type;
  },
  SET_OSSURL: (state, ossUrl) => {
    state.ossUrl = ossUrl;
  },
  SET_INFO: (state, data) => {
    state.info = data;
  },
  SET_MSGCOUNT: (state, data) => {
    state.msgCount = data;
  },
  SET_TIMER: (state, data) => {
    state.timer = data;
  },
  SET_AUDITCOUNT: (state, data) => {
    state.auditCount = data;
  },
  SET_AUDITTIMER: (state, data) => {
    state.auditTimer = data;
  }
};

const actions = {
  // user login
  login({ commit, state, dispatch }, userInfo) {
    const { username, password, type, fromType } = userInfo;
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        type: type,
        fromType: fromType
      })
        .then(response => {
          const { data } = response;
          commit("SET_TOKEN", data.accessToken);
          commit("SET_NAME", data.substationName);
          commit("SET_ID", data.userId);
          commit("SET_TYPE", data.userType);
          commit("SET_OSSURL", data.userType);

          setToken(data.accessToken);
          setOssUrl(data.ossUrl);
          setId(data.userId);
          setWorkerId(data.workerUserId ? data.workerUserId : "");

          getUserInfo({
            workerUserId: getWorkerId()
          })
            .then(res => {
              commit("SET_INFO", res.data);
              commit("SET_USERNAME", res.data.userInfo.yzbUser.loginName);
              commit("SET_AVATAR", res.data.userInfo.yzbUser.headUrl);
              getDict(); // 获取全部字典表
              // dispatch('getMassage')
              // dispatch('getAuditMassage')
            })
            .catch(err => {
              reject(error);
            });

          resolve(data);
        })
        .catch(error => {
          /* 测试用——直接跳转 */
          // setToken('123')
          // setOssUrl('test')
          // setId('test')
          reject(error);
        });
    });
  },
  // getMassage({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getMassageFuc()
  //     let timer = setInterval(() => {
  //       getMassageFuc()
  //     }, 10000)

  //     function getMassageFuc() {
  //       getMassage({}).then(res => {
  //         commit('SET_MSGCOUNT', res.data.msgCount)
  //         if (!state.timer) {
  //           commit('SET_TIMER', timer)
  //         }
  //       }).catch(err => {
  //         clearInterval(timer)
  //         commit('SET_TIMER', null)
  //       })
  //     }

  //     resolve()
  //   })
  // },
  // getAuditMassage({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getAuditMassageFuc()
  //     let timer = setInterval(() => {
  //       getAuditMassageFuc()
  //     }, 15000)

  //     function getAuditMassageFuc() {
  //       getAuditMassage({}).then(res => {
  //         commit('SET_AUDITCOUNT', res.data)
  //         if (!state.auditTimer) {
  //           commit('SET_AUDITTIMER', timer)
  //         }
  //       }).catch(err => {
  //         clearInterval(timer)
  //         commit('SET_AUDITTIMER', null)
  //       })
  //     }
  //     commit('SET_AUDITTIMER', timer)
  //     resolve()
  //   })
  // },
  // getMassageOnce({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getMassage({}).then(res => {
  //       commit('SET_MSGCOUNT', res.data.msgCount)
  //       resolve()
  //     })
  //   })
  // },
  // getAuditMassageOnce({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getAuditMassage({}).then(res => {
  //       commit('SET_AUDITCOUNT', res.data)
  //       resolve()
  //     })
  //   })
  // },
  // get user info
  getInfo({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      getUserInfo({
        workerUserId: getWorkerId()
      })
        .then(res => {
          commit("SET_INFO", res.data);
          commit("SET_ROLES", res.data.userInfo.roleInfo.id);
          commit("SET_USERNAME", res.data.userInfo.yzbUser.loginName);
          commit("SET_AVATAR", res.data.userInfo.yzbUser.headUrl);
          // if (!state.timer) {
          //   dispatch('getMassage')
          // }
          // if (!state.auditTimer) {
          //   dispatch('getAuditMassage')
          // }
          getDict(); // 获取全部字典表
          resolve(res);
        })
        .catch(err => {
          reject(err);
        });
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      //   logout(state.token).then(() => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      removeToken();
      resetRouter();
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch("tagsView/delAllViews", null, {
        root: true
      });
      commit("SET_TIMER", null);
      commit("SET_AUDITTIMER", null);
      resolve();
      //   }).catch(error => {
      //     reject(error)
      //   })
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("SET_ID", "");
      commit("SET_OSSURL", "");
      removeToken();
      removeOssUrl();
      removeId();
      resetRouter();
      resolve();
    });
  },
  // 动态地修改权限
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + "-token";

      commit("SET_TOKEN", token);
      setToken(token);

      const { roles } = await dispatch("getInfo");

      resetRouter();

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch("permission/generateRoutes", roles, {
        root: true
      });

      // dynamically add accessible routes
      router.addRoutes(accessRoutes);

      // reset visited views and cached views
      dispatch("tagsView/delAllViews", null, {
        root: true
      });

      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
